<%@ path=${filename}%>
<%@ include="dbentity/T_XG_DBETC.h"%>

<div><button v-show='databaseaccess>=0' @click='editDBRecord()' class='TextButton'><green>添加连接</green></div>

<%
	param_string(flag);

	if (flag.length() > 0)
	{
		param_string(type);
		param_string(name);
		param_string(host);
		param_string(port);
		param_string(user);
		param_string(step);
		param_string(stress);
		param_string(remark);
		param_string(enabled);
		param_string(charset);
		param_string(password);
		param_name_string(id);

		checkLogin();

		int res = 0;
		CT_XG_DBETC tab;

		tab.init(webx::GetDBConnect());
		tab.id = id;

		if (flag == "A" || flag == "U")
		{
			tab.host = host;
			tab.port = port;
			tab.user = user;
			tab.charset = charset;
			tab.password = password;

			if (type.length() > 0) tab.type = type;
			if (name.length() > 0) tab.name = name;
			if (step.length() > 0) tab.step = step;
			if (stress.length() > 0) tab.stress = stress;
			if (remark.length() > 0) tab.remark = remark;
			if (enabled.length() > 0) tab.enabled = enabled;

			tab.statetime.update();

			if (flag == "A")
			{
				res = tab.insert();
			}
			else
			{
				res = tab.update();

				typedef DBConnectPool* (*GetDBConnectPoolFunc)(const char*);
				static GetDBConnectPoolFunc getPool = (GetDBConnectPoolFunc)Process::GetObject("HTTP_GET_DBCONNECT_POOL_FUNC");

				if (tab.find() && tab.next() && tab.enabled.val() > 0)
				{
					DBConnectPool* pool = getPool(id.c_str());

					if (pool)
					{
						YAMLoader cfg;

						cfg.set("database.host", tab.host.val());
						cfg.set("database.user", tab.user.val());
						cfg.set("database.name", tab.name.val());
						cfg.set("database.port", tab.port.val());
						cfg.set("database.charset", tab.charset.val());
						cfg.set("database.password", tab.password.val());

						pool->init(&cfg);
					}

					webx::ReloadSystemConfig();
				}
			}
		}
		else if (flag == "D")
		{
			res = tab.remove();
		}

		return simpleResponse(res);
	}

	webx::PrintRecordview(out, "${database}");
%>

<style>
#DBSyncButton{
	margin-left: 2px;
}
#DatabaseEditTable td{
	padding: 6px;
}
</style>

<script>
{
	var databaseaccess = getAccess('${filename}');

	$recordvmdata.title = {
		id: '连接名称',
		type: '连接类型',
		name: '数据库名',
		host: '连接地址',
		port: '监听端口',
		user: '连接用户',
		charset: '字符编码',
		enabled: '数据用途'
	};

	$recordvmdata.button = [{
		title: '编辑',
		click: editDBRecord,
		disable: databaseaccess < 0
	},{
		title: '删除',
		click: removeDBRecord,
		disable: databaseaccess < 0
	},{
		title: '发布',
		click: publishDBRecord,
		disable: databaseaccess < 0
	}];

	function checkHost(host){
		var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
		return reg.test(host);
	}

	function editDBRecord(item){
		var title = item ? '更新连接' : '添加连接';
		var msgbox = showConfirmMessage("<table id='DatabaseEditTable'>"
			+ "<tr><td><v-select id='DBUsedText' title='数据用途' option='停用|系统|用户'></v-select></td></tr>"
			+ "<tr><td><v-select id='DBCharText' title='字符编码' option='默认|GBK|UTF'></v-select></td></tr>"
			+ "<tr><td><v-select id='DBTypeText' title='连接类型' option='MYSQL|SQLITE'></v-select></td></tr>"
			+ "<tr><td><v-text id='DBIdText' title='连接名称' maxlength='32' size='13'></v-text><v-button id='DBSyncButton' title='同步配置'></v-button></td></tr>"
			+ "<tr><td><v-text id='DBNameText' title='数据库名' maxlength='128' size='24'></v-text></td></tr>"
			+ "<tr><td><v-text id='DBHostText' title='连接地址' maxlength='32' size='24'></v-text></td></tr>"
			+ "<tr><td><v-text id='DBPortText' title='监听端口' maxlength='5' size='24'></v-text></td></tr>"
			+ "<tr><td><v-text id='DBUserText' title='连接用户' maxlength='32' size='24'></v-text></td></tr>"
			+ "<tr><td><v-text id='DBPasswdText' title='连接密码' type='password' maxlength='32' size='24'></v-text></td><td><img src='/res/img/eyeclose.png'/></td></tr>",
			title, function(flag){
			if (flag == 0) return true;

			var id = $('#DBIdText').val();
			var type = $('#DBTypeText').val();
			var name = $('#DBNameText').val();
			var host = $('#DBHostText').val();
			var port = $('#DBPortText').val();
			var user = $('#DBUserText').val();
			var enabled = $('#DBUsedText').val();
			var charset = $('#DBCharText').val();
			var password = $('#DBPasswdText').val();

			if (strlen(id) == 0){
				$('#DBIdText').focus();
				return false;
			}

			if (strlen(name) == 0){
				$('#DBNameText').focus();
				return false;
			}

			var param = {};
			var typelist = ['mysql', 'sqlite'];
			var charlist = ['', 'GBK', 'UTF-8'];

			type = typelist[type];
			charset = charlist[charset];

			if (item && charset == item.charset
				&& id == item.id && type == item.type
				&& name == item.name && host == item.host
				&& port == item.port && user == item.user
				&& password == item.password && enabled == item.enabled){
				return true;
			}
			
			if (item == null){
				var found = false;

				$('.DBIdTd').each(function(){
					if (id == $(this).text()) found = true;
				});

				if (found){
					msgbox.title('连接名称重复');

					$('#DBIdText').focus();

					setTimeout(function(){
						msgbox.title(title);
					}, 1000);

					return false;
				}
			}

			param['id'] = id;
			param['type'] = type;
			param['name'] = name;
			param['enabled'] = enabled;
			param['charset'] = charset;

			if (type == 'mysql'){
				if (strlen(host) == 0){
					$('#DBHostText').focus();
					return false;
				}

				if (!checkHost(host)){
					$('#DBHostText').val('').focus();
					return false;
				}

				if (strlen(port) == 0){
					$('#DBPortText').focus();
					return false;
				}
				
				if (strlen(user) == 0){
					$('#DBUserText').focus();
					return false;
				}
				
				if (strlen(password) == 0){
					$('#DBPasswdText').focus();
					return false;
				}
				
				param['host'] = host;
				param['port'] = port;
				param['user'] = user;
				param['password'] = password;
			}

			param['flag'] = item ? 'U' : 'A';
			param['step'] = '1';
			param['stress'] = '0';

			getHttpResult('/${filename}', param, function(data){
				if (data.code == XG_TIMEOUT){
					sessionTimeout();
				}
				else if (data.code == XG_AUTHFAIL){
					showNoAccessToast();
				}
				else if (data.code < 0){
					showToast(item ? '修改数据库连接失败' : '添加数据库连接失败');
				}
				else{
					$recordvmdata.reload();
					showToast(item ? '修改数据库连接成功' : '添加数据库连接成功');
				}
			});
		});
		
		function updateParam(item, sync){
			if (item == null){
				$('#DBUsedText').val(1);
				$('#DBTypeText').val(0);
				return false;
			}

			$('#DBIdText').val(item.id);
			$('#DBNameText').val(item.name);
			$('#DBHostText').val(item.host);
			$('#DBPortText').val(item.port);
			$('#DBUserText').val(item.user);
			$('#DBUsedText').val(item.enabled);
			$('#DBPasswdText').val(item.password);

			$('#DBTypeText').val(0);
			$('#DBCharText').val(0);

			if (item.type == 'sqlite') $('#DBTypeText').val(1);
			if (item.charset == "GBK") $('#DBCharText').val(1);
			if (item.charset == "UTF-8") $('#DBCharText').val(2);

			if (sync == null){
				$('#DBIdText').attr('disabled', true);
			}

			$('#DBTypeText').change();

			return true;
		}

		$('#DBPasswdText').parent().parent().next().children('img').width('16px').height('16px').css('margin-top', '4px').css('margin-left', '3px').click(function(){
			if (this.src.indexOf('close') > 0){
				this.src = '/res/img/eyeopen.png';
				$('#DBPasswdText').attr('type', 'text');
			}
			else{
				this.src = '/res/img/eyeclose.png';
				$('#DBPasswdText').attr('type', 'password');
			}
		});

		$('#DBSyncButton').click(function(){
			var id = $('#DBIdText').val();

			if (strlen(id) == 0){
				$('#DBIdText').focus();
				return false;
			}

			msgbox.title('正在同步配置...');

			getHttpResult('/execmodule', {cmd: 'get', type: 'database', name: id}, function(data){
				if (data.code == XG_TIMEOUT){
					sessionTimeout();
				}
				else if (data.code == XG_AUTHFAIL){
					showNoAccessToast();
				}
				else if (data.code < 0){
					msgbox.title('配置信息同步失败');
				}
				else{
					var found = null;

					$.each(data.list, function(idx, item){
						if (id == item.id){
							updateParam(item, true);
							found = item;
							return true;
						}
					});

					if (found == null){
						msgbox.title('没有相关配置信息');
					}
					else{
						msgbox.title('配置信息已同步');
					}
				}

				setTimeout(function(){
					msgbox.title(title);
				}, 2000);
			});
		});

		$('#DBTypeText').change(function(){
			if ($(this).val() == 0){
				$('#DBHostText').removeAttr('disabled').prev().css('color', '#000');
				$('#DBPortText').removeAttr('disabled').prev().css('color', '#000');
				$('#DBUserText').removeAttr('disabled').prev().css('color', '#000');
				$('#DBPasswdText').removeAttr('disabled').prev().css('color', '#000');
			}
			else{
				$('#DBHostText').attr('disabled', true).prev().css('color', '#888');
				$('#DBPortText').attr('disabled', true).prev().css('color', '#888');
				$('#DBUserText').attr('disabled', true).prev().css('color', '#888');
				$('#DBPasswdText').attr('disabled', true).prev().css('color', '#888');
			}
		});

		$('#DBPortText').keyup(function(){
			this.value = this.value.replace(/[^\0-9]/g, '');
		}).change(function(){
			this.value = this.value.replace(/[^\0-9]/g, '');
		});

		updateParam(item);
	}

	function removeDBRecord(item){
		showConfirmMessage('是否决定删除[' + item.id + ']连接？', '删除连接', function(flag){
			if (flag){
				getHttpResult('/${filename}', {flag: 'D', id: item.id}, function(data){
					if (data.code == XG_TIMEOUT){
						sessionTimeout();
					}
					else if (data.code == XG_AUTHFAIL){
						showNoAccessToast();
					}
					else if (data.code < 0){
						showToast('删除数据库连接失败');
					}
					else{
						$recordvmdata.reload();
						showToast('删除数据库连接成功');
					}
				});
			}
		});
	}

	function publishDBRecord(item){
		showConfirmMessage('是否决定发布[' + item.id + ']配置？', '发布配置', function(flag){
			if (flag){
				var param = 'cmd=sync&type=database&name=' + item.id;

				getHttpResult('/broadcast', {path: 'execmodule', param: param}, function(data){
					if (data.code == XG_TIMEOUT){
						sessionTimeout();
					}
					else if (data.code == XG_AUTHFAIL){
						showNoAccessToast();
					}
					else if (data.code < 0){
						showToast('发布配置失败');
					}
					else{
						showToast('发布配置成功');
					}
				});
			}
		});
	}
}
</script>